package myDaos;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.entities.InvoiceDetailsInfo;


@Stateless
public class InvoiceDetailsDao {

	@PersistenceContext(unitName = "UnileverProcedure")
    private EntityManager em;
	
	public EntityManager getEntityManager() {
        return em;
    }
	
	public List<InvoiceDetailsInfo> getInvoiceDetailsList(String distributor,Date from,Date to)
	{
		List<InvoiceDetailsInfo> idlist=null;
		try {
			StringBuffer queryBiffer = new StringBuffer();
			queryBiffer.append("SELECT i FROM InvoiceDetailsInfo i WHERE 1=1"); 	
			
			if(distributor!=null && !distributor.trim().equals(""))
    	    {
				queryBiffer.append(" AND i.distributorid = :distributorid") ;	
    	    }
				
			if(from!=null)
    	    {
				queryBiffer.append("  AND trunc(i.invoicedate) >= trunc(:fDate)") ;	
    	    }

			if(to!=null)
    	    {
				queryBiffer.append("  AND trunc(i.invoicedate) <= trunc(:tDate)") ;	
    	    }
			
			
			System.out.println(queryBiffer.toString());
			
			Query q = getEntityManager().createQuery(queryBiffer.toString());

			if(distributor!=null && !distributor.trim().equals("")){q.setParameter("distributorid", distributor);}
			if(from!=null){q.setParameter("fDate", from);}
			if(to!=null){q.setParameter("tDate", to);}
			
			    idlist = q.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return idlist;
	}

}

